<template>
  <div class='tinymce'>
    <h4 style="margin:0 0 20px 0">
      <el-row>
        <el-col :span="19">
          <span v-if="editData">编辑商品</span>
          <span v-else>添加商品</span>
        </el-col>
        <el-col :span="5" style="text-align:right">
          <i class="el-icon-error" style="background:#e6e6e6" @click="goBack"></i>
        </el-col>
      </el-row>
    </h4>
    <div>
      
     <el-form  label-position="left" label-width="80px" :rules="rules" ref="formAling" :model="formLabelAlign">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formLabelAlign.title"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="title">
          <el-select v-model="formLabelAlign.typeId" placeholder="请选择">
            <el-option v-for="item in otypes" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="title">
           <el-checkbox-group v-model="tagsValue">
            <el-checkbox v-for="item in tags" :key="item.name"  :label="item.id">{{item.name}}</el-checkbox>
            
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="formLabelAlign.price" style="width:200px"></el-input>
          <span>原价：</span>
           <el-input v-model="formLabelAlign.originalPrice" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="push_time">
          <el-date-picker v-model="formLabelAlign.beginTime" type="datetime" value-format="timestamp" placeholder="选择日期时间"> </el-date-picker>
          至
          <el-date-picker v-model="formLabelAlign.endTime" type="date" format="yyyy 年 MM 月 dd 日" value-format="timestamp" placeholder="选择日期"></el-date-picker>
          <span style="color:#ccc">过期后用户未消费将自动退款</span>
        </el-form-item>
        <el-form-item label="封面" prop="title">
          <el-upload 
            class="avatar-uploaderInfo"
            action="https://upload.qiniup.com/"
            :show-file-list="false"
            :on-success="handleOkLogo"
            :before-upload="beforeAvatarUpload"
            :data="postData">
            <img v-if="formLabelAlign.header_url" :src="formLabelAlign.header_url" class="avatarInfo">
            <i v-else class="el-icon-plus avatar-uploader-iconInfo"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      
      <el-row>
        <div >
          <div class="initbox">
            <el-button class="initBtn" @click="upImageFun">图</el-button>
            <editor id='tinymce' v-model='tinymceHtml' :init='init'> </editor>
            
          </div>

          <el-button type="success" @click="submitArticle('formAling')">保存文章</el-button>
        </div>
      </el-row>
    
    </div>
    <el-dialog :visible.sync="imgstuts">
      <el-upload
        class="upload-demo"
        action="https://upload.qiniup.com/"
        :on-success="handleOkContent"
        ref="upload"
        :data="postData"
        multiple
       
        >
        <el-button size="small" type="primary">添加图片</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="backFun">取 消</el-button>
        <el-button type="primary" @click="apendHtml">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Http from '@/Http/Http'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'

export default {
  name: 'tinymce',
  props:['editData'],
  data () {
    const title = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        callback()
      }
    }
    
    return {
     
      postData:{
        token:'',
      },
      tokenimgUrl:'',
      dialogImageUrl: '',
      dialogVisible: false,
      otypes:'', //类型
      tags:'', //标签
      tagsValue:[],
      formLabelAlign:{
        title:'',
        typeId:'', //类型
        price:'', //价格
        originalPrice:'', //原价
        endTime:'', //结束时间
        beginTime:'',//开始时间
        introduction:'',
        is_timer:'1',
        push_time:'',
        header_url:'' //封面
      },
      rules:{
        title:[
          {validator:title,trigger:'blur'}
        ]
      },

      imgstuts:false, //富文本编辑器部分
      tinymceHtml:'',
      fileList:[],
      init: {
        language_url: '/static/tinymce/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/static/tinymce/skins/lightgray',
        height: 300,
        plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
        toolbar:
          'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image | removeformat',
        branding: false
      }
    }
    
  },

  mounted () {
    
  },
  created() {
    console.log(this.editData)
    this.getToken()
  },
  methods:{
    getToken() {
      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      Http.getCommoTypes()
      .then( res => {
        this.otypes = res.data.data
      })
      Http.getCommoTags()
      .then( res => {
        this.tags = res.data.data
      })
      .catch( error => {
        this.$router.push('/')
        console.log(error)
      });
      if (this.editData) {
        this.formLabelAlign.title = this.editData.title;
        this.formLabelAlign.typeId = this.editData.type;
        this.formLabelAlign.price = this.editData.price;
        this.formLabelAlign.originalPrice = this.editData.originalPrice;
        this.formLabelAlign.header_url = this.editData.cover;
        this.formLabelAlign.beginTime = this.editData.beginTime;
        this.formLabelAlign.endTime = this.editData.endTime;
        this.tinymceHtml = this.editData.introduction;
        this.tagsValue = []; //标签
      }
    },
   
    submitArticle(val) {
      this.$refs[val].validate((valid) => {
        if (valid) {
          if (!this.tinymceHtml) { this.$message.error('请输入推送内容'); return }
          const articleContent = this.tinymceHtml.replace(/20%/g,'100%');
          const param = {
            "title":this.formLabelAlign.title,  //商品标题
            "type":this.formLabelAlign.typeId,  //类型 
            "price":this.formLabelAlign.price,
            "originalPrice" : this.formLabelAlign.originalPrice, //原价
            "cover" : this.formLabelAlign.header_url,
            "markIds":this.tagsValue,
            "beginTime" : this.formLabelAlign.beginTime,
            "endTime" : this.formLabelAlign.endTime,
            "introduction":articleContent, // 文章内容  实体列表 
          }
          console.log(param)
          this.editData ? this.EditPushFun(param) : this.addAPushFun(param)
        } else {
          this.$message.error('请填写标题')
        }
      })
      
    },
    addAPushFun(param) {
      console.log('添加商品信息')
      Http.addCommoInsert(param)
        .then( res => {
          if( res.data.code == 200 ){
            this.$message.success('商品信息添加成功')
            this.goBack()         
          } else if(res.data.code == -1003) {
            this.$message.error(`请求失败原因：${res.data.message}`)
            this.$router.push('/')
          }
        })
        .catch( error => {
          this.$message.error('服务器请求失败')
        })
    },
    EditPushFun(param) {
      param.id = this.editData.id;
      console.log('xiugai ')
      return
      Http.editCommo(param)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('推送修改成功')
          this.goBack()         
        } else if(res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          this.$router.push('/')
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
      })
    },
    handleOkLogo(responed) {
      console.log(responed)
      this.formLabelAlign.header_url = `http://${this.tokenimgUrl}/${responed.key}`;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      if (isJPG || isPNG) {
        return true;
      } else {
          this.$message.error('上传图片格式不正确!');
        return false;
      }
    },
    goBack(){
      this.$emit('getlist')
    },
    
    //富文本编辑器部分
    upImageFun(){
      this.imgstuts = true
      console.log(11122)
    },
    handleOkContent(responed){
      this.fileList.push(`http://${this.tokenimgUrl}/${responed.key}`)
      console.dir(this.fileList)
      console.log(this.fileList)
    },
    backFun(){
      this.imgstuts = false;
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    },
    apendHtml(){
      console.dir(this.fileList)
      console.log(this.tinymceHtml)
      let arrHtml='';
      this.fileList.forEach(item => {
        arrHtml += `<img style="width:20%" src="${item}" alt=""/>`;
      })
      this.tinymceHtml = `${this.tinymceHtml}${arrHtml}`;
      console.log(this.tinymceHtml)
      this.imgstuts = false
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    }
  },
  components: {
    Editor,
  }
}
</script>
<style>
.el-textarea__inner{
  height:146px
}
.initbox{
  position: relative;
}
.initBtn{
  position: absolute;
  opacity: 0;
  position: absolute;
  z-index: 2;
  top: 36px;
  left: 786px;
  width: 30px;
  padding: 0;
  height: 33px;
  border: 1px solid red;
}

#tinymce_ifr{
  height:500px !important
}

.disabled .el-upload--picture-card {
    display: none;
}
.avatar-uploaderInfo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploaderInfo .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-iconInfo {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatarInfo {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
